const state = {
    recipients: [],
    subjectTemplate: "",
    bodyTemplate: "",
};

const recipientsInput = document.getElementById("recipientsFile");
const subjectInput = document.getElementById("subjectFile");
const bodyInput = document.getElementById("bodyFile");
const organizerInput = document.getElementById("organizerName");
const loadButton = document.getElementById("loadButton");
const statusBlock = document.getElementById("status");
const previewSection = document.getElementById("preview");
const recipientSelect = document.getElementById("recipientSelect");
const subjectPreview = document.getElementById("subjectPreview");
const bodyPreview = document.getElementById("bodyPreview");

loadButton.addEventListener("click", async () => {
    if (!recipientsInput.files.length) {
        updateStatus("请先选择收件人 CSV 文件。", true);
        return;
    }
    if (!subjectInput.files.length) {
        updateStatus("请先选择主题模板文件。", true);
        return;
    }
    if (!bodyInput.files.length) {
        updateStatus("请先选择正文模板文件。", true);
        return;
    }

    updateStatus("正在加载文件...", false);
    try {
        const [csvText, subjectText, bodyText] = await Promise.all([
            readFileText(recipientsInput.files[0]),
            readFileText(subjectInput.files[0]),
            readFileText(bodyInput.files[0]),
        ]);

        const recipients = parseCsv(csvText);
        if (!recipients.length) {
            updateStatus("CSV 中未找到有效的收件人信息。", true);
            return;
        }

        state.recipients = recipients;
        state.subjectTemplate = subjectText;
        state.bodyTemplate = bodyText;

        populateRecipients(recipients);
        updateStatus(`已加载 ${recipients.length} 位收件人。`, false);
        previewSection.classList.remove("hidden");
        renderPreview(recipientSelect.value);
    } catch (error) {
        console.error(error);
        updateStatus(`加载文件失败：${error.message}`, true);
        previewSection.classList.add("hidden");
    }
});

recipientSelect.addEventListener("change", () => {
    renderPreview(recipientSelect.value);
});

organizerInput.addEventListener("input", () => {
    if (!previewSection.classList.contains("hidden")) {
        renderPreview(recipientSelect.value);
    }
});

function readFileText(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = () => reject(new Error(`无法读取 ${file.name}`));
        reader.readAsText(file);
    });
}

function parseCsv(text) {
    const rows = [];
    let currentRow = [];
    let currentField = "";
    let inQuotes = false;

    for (let i = 0; i < text.length; i += 1) {
        const char = text[i];
        const nextChar = i + 1 < text.length ? text[i + 1] : "";

        if (char === '"' && inQuotes && nextChar === '"') {
            currentField += '"';
            i += 1;
        } else if (char === '"') {
            inQuotes = !inQuotes;
        } else if (char === "," && !inQuotes) {
            currentRow.push(currentField);
            currentField = "";
        } else if ((char === "\n" || char === "\r") && !inQuotes) {
            if (char === "\r" && nextChar === "\n") {
                i += 1;
            }
            currentRow.push(currentField);
            currentField = "";
            if (currentRow.length > 1 || currentRow[0] !== "") {
                rows.push(currentRow);
            }
            currentRow = [];
        } else {
            currentField += char;
        }
    }

    if (currentField !== "" || currentRow.length) {
        currentRow.push(currentField);
        rows.push(currentRow);
    }

    if (!rows.length) {
        return [];
    }

    const header = rows[0].map((col) => col.trim());
    const records = [];

    for (let i = 1; i < rows.length; i += 1) {
        const row = rows[i];
        if (row.every((value) => value.trim() === "")) {
            continue;
        }
        const entry = {};
        header.forEach((key, index) => {
            entry[key] = (row[index] ?? "").trim();
        });
        records.push(entry);
    }

    return records;
}

function populateRecipients(recipients) {
    recipientSelect.innerHTML = "";
    recipients.forEach((recipient, index) => {
        const option = document.createElement("option");
        const displayName = recipient.name || recipient.Name || `收件人 ${index + 1}`;
        option.value = index.toString();
        option.textContent = `${displayName} <${recipient.email ?? recipient.Email ?? "未知邮箱"}>`;
        recipientSelect.appendChild(option);
    });
}

function renderPreview(indexValue) {
    const index = parseInt(indexValue, 10);
    if (Number.isNaN(index) || index < 0 || index >= state.recipients.length) {
        subjectPreview.textContent = "";
        bodyPreview.textContent = "";
        return;
    }

    const recipient = state.recipients[index];
    const organizerName = organizerInput.value.trim() || "会议组织者";

    const data = {
        ...recipient,
        organizer_name: organizerName,
    };

    subjectPreview.textContent = applyTemplate(state.subjectTemplate, data);
    bodyPreview.textContent = applyTemplate(state.bodyTemplate, data);
}

function applyTemplate(template, data) {
    return template.replace(/\{(\w+)\}/g, (match, key) => {
        if (Object.prototype.hasOwnProperty.call(data, key)) {
            return data[key];
        }
        return match;
    });
}

function updateStatus(message, isError) {
    statusBlock.innerHTML = "";
    const paragraph = document.createElement("p");
    paragraph.textContent = message;
    paragraph.className = isError ? "error" : "";
    statusBlock.appendChild(paragraph);
    statusBlock.classList.toggle("status-error", isError);
}
